# encoding: utf-8
import sys, re

reload(sys)
sys.setdefaultencoding("utf-8")

from xml.dom.minidom import parse
import xml.dom.minidom
import xml
from xml.dom import minidom

def fixed_writexml(self, writer, indent="", addindent="", newl=""):
    # indent = current indentation
    # addindent = indentation to add to higher levels
    # newl = newline string
    writer.write(indent+"<" + self.tagName)

    attrs = self._get_attributes()
    a_names = attrs.keys()
    a_names.sort()

    for a_name in a_names:
        writer.write(" %s=\"" % a_name)
        minidom._write_data(writer, attrs[a_name].value)
        writer.write("\"")
    if self.childNodes:
        if len(self.childNodes) == 1 \
          and self.childNodes[0].nodeType == minidom.Node.TEXT_NODE:
            writer.write(">")
            self.childNodes[0].writexml(writer, "", "", "")
            writer.write("</%s>%s" % (self.tagName, newl))
            return
        writer.write(">%s"%(newl))
        for node in self.childNodes:
            if node.nodeType is not minidom.Node.TEXT_NODE:
                node.writexml(writer,indent+addindent,addindent,newl)
        writer.write("%s</%s>%s" % (indent,self.tagName,newl))
    else:
        writer.write("/>%s"%(newl))

minidom.Element.writexml = fixed_writexml

def replaceJarVersion(path, jarObj, isAddProperties = False, isCheckDependencies = True):
    """
    替换pom文件内的jar工程版本
    :param path:
    :param jarObj: {'spi':{'groupId':'com.winit','version':'1.1.1.aaaaa','key':'spi.version'},
                    'winit-core':{'groupId':'com.winit','version':'1.1.1.aaaaa','key':'winit.core.version'}}
    :param isAddProperties:  version使用$ 且 properties内不存在配置时 是否创建
    :param isCheckDependencies:  是否检查pom的dependencies下是否存在jar工程
    :return:
    """

    if len(jarObj) == 0:
        return

    DOMTree = xml.dom.minidom.parse(path)
    Data = DOMTree.documentElement

    # type = '0'  # 在properties中配置版本号
    type = '1'  # 直接在dependency中配置版本号

    if isCheckDependencies:
        _list = Data.getElementsByTagName('dependencies')
        for de in _list:
            dependencies = de.getElementsByTagName('dependency')
            for dependency in dependencies:
                artifactId = dependency.getElementsByTagName('artifactId')[0].childNodes[0].data
                if jarObj.has_key(artifactId):
                    versions = dependency.getElementsByTagName('version')
                    if len(versions) != 0:
                        element = dependency.getElementsByTagName('version')[0]
                        _v = element.childNodes[0].data
                        if '$' in str(_v):
                            type = '0'
                        else:
                            type = '1'
                        updateValue(DOMTree, element, jarObj[artifactId]['version'], isAddProperties = isAddProperties)
                        jarObj.pop(artifactId)

        #原pom文件中不存在jar工程时,自动添加
        # if len(jarObj) > 0:
        #     if len(_list) > 0:
        #         for _key in jarObj:
        #             _dependency = createDependencie(DOMTree, _key, jarObj[_key], type, isAddProperties)
        #             Data.getElementsByTagName('dependencies')[0].appendChild(_dependency)
        #     else:
                # 先添加dependencies 再添加dependencie
                # _dependencys = DOMTree.createElement('dependencies')
                # for _key in jarObj:
                #     _dependency = createDependencie(DOMTree, _key, jarObj[_key], type, isAddProperties)
                #     _dependencys.appendChild(_dependency)
                # Data.appendChild(_dependencys)
    else:
        for _key in jarObj:
            updateValueInProperties(DOMTree, jarObj[_key]['key'], jarObj[_key]['version'], isAdd = isAddProperties)

    xmlfile = open(path, 'w')
    # DOMTree.writexml(xmlfile, addindent = ' ' * 2, encoding = 'UTF-8')
    DOMTree.writexml(xmlfile, indent='',addindent='\t',newl='\n', encoding = 'UTF-8')
    xmlfile.close()


def createDependencie(DOMTree, jarName, jarObj, type, isAddProperties = False):
    _artifactIdNode = DOMTree.createTextNode(jarName)
    _artifactId = DOMTree.createElement('artifactId')
    _artifactId.appendChild(_artifactIdNode)

    _groupIdNode = DOMTree.createTextNode(jarObj['groupId'])
    _groupId = DOMTree.createElement('groupId')
    _groupId.appendChild(_groupIdNode)

    _dependency = DOMTree.createElement('dependency')
    _dependency.appendChild(_artifactId)
    _dependency.appendChild(_groupId)

    if type == '1':  # 直接在dependency中配置版本号
        _versionNode = DOMTree.createTextNode(jarObj['version'])
        _version = DOMTree.createElement('version')
        _version.appendChild(_versionNode)
        _dependency.appendChild(_version)
    elif type == '0':  # 在properties中配置版本号
        _versionNode = DOMTree.createTextNode('${%s}' % jarObj['key'])
        _version = DOMTree.createElement('version')
        _version.appendChild(_versionNode)
        _dependency.appendChild(_version)
        updateValueInProperties(DOMTree, jarObj['key'], jarObj['version'], isAdd = isAddProperties)

    return _dependency


def replaceProVersion(path, newVersion, isAddProperties = False, isUpdate = False):
    """
    修改pom文件版本
    :param path:
    :param newVersion:
    :param isAddProperties:  根目录下version使用$ 且 properties内不存在配置时 是否创建
    :param isUpdate:更新pom版本为release
    :return:
    """
    DOMTree = xml.dom.minidom.parse(path)
    Data = DOMTree.documentElement

    _v = None

    _versions = Data.getElementsByTagName('version')
    for _version in _versions:
        if _version.parentNode.tagName == 'project':
            _v = updateValue(DOMTree, _version, newVersion, isAddProperties = isAddProperties, isUpdate = isUpdate)
            break

    xmlfile = open(path, 'w')
    # DOMTree.writexml(xmlfile, addindent = ' ' * 2, encoding = 'UTF-8')
    DOMTree.writexml(xmlfile, indent='',addindent='\t',newl='\n', encoding = 'UTF-8')
    xmlfile.close()
    return _v


def updateValue(DOMTree, element, newVersion, isAddProperties = False, isUpdate = False):
    _v = element.childNodes[0].data
    if '$' in str(_v):
        # 1、version下保存的为版本号key值，value保存在properties内
        _key = str(_v).replace('${', '').replace('}', '')
        _v = updateValueInProperties(DOMTree, _key, newVersion, isAdd = isAddProperties, isUpdate = isUpdate)
    else:
        # 2、version下保存的为版本号
        if isUpdate:
            if re.search('SNAPSHOT', str(_v), re.IGNORECASE):
                element.childNodes[0].data = re.sub("SNAPSHOT", "RELEASE", _v, flags = re.IGNORECASE)
            else:
                element.childNodes[0].data = '%s.RELEASE' % _v
        else:
            element.childNodes[0].data = newVersion
    return _v


def updateValueInProperties(DOMTree, _key, _value, isAdd = False, isUpdate = False):
    """
    修改pom文件properties里的配置
    :param DOMTree:
    :param _key: 要修改配置的key值
    :param _value:要修改配置的value值
    :param isAdd:当key不存在的时候 是否添加 默认不添加
    :param isUpdate:更新pom版本为release
    :return:
    """
    Data = DOMTree.documentElement
    _properties = Data.getElementsByTagName('properties')
    _v = None
    _count = 0
    for _propertie in _properties:
        if _propertie.parentNode.tagName == 'project':
            _count = 1
            _keyEles = _propertie.getElementsByTagName(_key)
            if len(_keyEles) == 0:
                if isAdd:
                    _valueNode = DOMTree.createTextNode(_value)
                    _keyEle = DOMTree.createElement(_key)
                    _keyEle.appendChild(_valueNode)

                    _propertie.appendChild(_keyEle)
            else:
                _v = _keyEles[0].childNodes[0].data
                if isUpdate:
                    if re.search('SNAPSHOT', str(_v), re.IGNORECASE):
                        _keyEles[0].childNodes[0].data = re.sub("SNAPSHOT", "RELEASE", _v, flags = re.IGNORECASE)
                    else:
                        _keyEles[0].childNodes[0].data = '%s.RELEASE' % _v
                else:
                    _keyEles[0].childNodes[0].data = _value

    if _count == 0 and isAdd:
        _valueNode = DOMTree.createTextNode(_value)
        _keyEle = DOMTree.createElement(_key)
        _keyEle.appendChild(_valueNode)

        _propertie = DOMTree.createElement('properties')
        _propertie.appendChild(_keyEle)

        Data.appendChild(_propertie)

    return _v

# if __name__ == '__main__':
#     jarObj = {
#         'spi': {'groupId': 'com.winit', 'version': '1.1.1.aaaaa', 'key': 'spi.version'},
#         'winit-core': {'groupId': 'com.winit', 'version': '1.1.1.aaaaa', 'key': 'winit.core.version'},
#     }
#     path = "/Users/wangjian/Desktop/test/ebay-adapter/pom.xml"

# print replaceProVersion(path, '222')
# print replaceJarVersion(path, jarObj)
